/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-03-16 14:29:29
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-03-25 11:45:23
 */

const {
    request
} = require('./../utils/request.js')

const appInst =  getApp();

class Common {
    constructor() {

    }
    /**
     * 操作上传文件
     * 
     * @param {any} data 
     * 
     * @memberOf Goods
     */
    handleUpload(data,cbk) {
        function upload(url){
            return new Promise((resolve, reject) => {
                const uploadTask = wx.uploadFile({
                    url: 'http://172.16.1.40/app/upload/single',
                    name: 'file',
                    header: {
                        token: appInst.data.token
                    },
                    filePath: url,
                    formData: {
                        type: data.type
                    },
                    success: (res) => {
                        resolve(res.data)
                    },
                    fail: () => {
                        reject('fail')
                    },
                    complete: () => {}
                });
                uploadTask.onProgressUpdate((res) => {
                    typeof cbk==='function' && cbk(res.progress,res.totalBytesSent,res.totalBytesExpectedToSend)
                  })
            })
        }
        //传递一个数组，循环该数组上传
        let promisees = []
        if(typeof data.file!=='string'){
           data.file.map(item=>{
                promisees.push(
                    upload(item)
                )
           })
        }else{
            return upload(file)
        }

        // 返回所有状态
        return Promise.all(promisees).then(res=>{
            wx.hideLoading();
            return res
        }).catch(err=>{
            return err
        })
       
        // return request.post('/upload/single',data)
    }

}

exports.commonAPI = new Common